package com.ptbuy.tranrecord.product;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ptbuy.R;
import com.ptbuy.adapter.MediaPagerAdapter;
import com.ptbuy.callback.ExportMsgCall;
import com.ptbuy.db.dao.ClientDao;
import com.ptbuy.db.dao.ExportDao;
import com.ptbuy.db.dao.ProductDao;
import com.ptbuy.db.pojo.ClientPojo;
import com.ptbuy.db.pojo.ExportPojo;
import com.ptbuy.db.pojo.ProductPojo;
import com.ptbuy.signature.SingDialogAcvity;
import com.ptbuy.tranrecord.TranRecordActivity;
import com.ptbuy.tranrecord.adapter.ExportViewAdapter;
import com.ptbuy.tranrecord.product.adapter.RecyclerProductViewAdapter;
import com.ptbuy.upload.Upload;
import com.ptbuy.utils.Constants;
import com.ptbuy.utils.ExportUtils;
import com.ptbuy.utils.MineType;
import com.ptbuy.utils.ToastUtil;
import com.ptbuy.utils.Utils;
import com.scwang.smart.refresh.footer.BallPulseFooter;
import com.scwang.smart.refresh.header.BezierRadarHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

public class TranProductActivity extends AppCompatActivity {


    private String spqParam = "";
    private ProductDao productDao;
    private ClientDao clientDao;
    String pid;

    //总件数、总价、选中总价、选中总件数
    private TextView numTotalProduct, numTotalPrice;
    private int limit = 10;
    private int offset = 0;
    private SmartRefreshLayout smartRefreshLayout;
    private RecyclerView recyclerView;
    private LinearLayout historicalEmpty;
    private List<ProductPojo> items;
    private String sqlParam = "";
    private RecyclerProductViewAdapter adapter;

    private Upload upload;


    String productNameScreenText, productPriceMinScreenText, productPriceMaxScreenText, recordBeginTimeText, recordEndTimeText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tran_product_activity);

        productDao = new ProductDao();
        clientDao = new ClientDao();
        upload = new Upload();
        pid = getIntent().getExtras().getString("pid");

        findViewById(R.id.productBack).setOnClickListener(v -> back());

        findViewById(R.id.recordProductExport).setOnClickListener(v -> recordExport());

        //声明绑定控件
        smartRefreshLayout = findViewById(R.id.product_smart_refresh_layout);
        recyclerView = findViewById(R.id.product_recycler_view);

        init();

        //设置刷新逻辑
        setRefresh();
        numTotalProduct = findViewById(R.id.numTotalProduct);
        numTotalPrice = findViewById(R.id.numTotalPrice);
        mathPrice();
        LinearLayout screenContent = findViewById(R.id.screenContent);//查询框
        EditText productNameScreen = findViewById(R.id.productNameScreen);//商品名称
        EditText productPriceMinScreen = findViewById(R.id.productPriceMinScreen);//最小值
        EditText productPriceMaxScreen = findViewById(R.id.productPriceMaxScreen);//最大值
        TextView recordBeginTime = findViewById(R.id.recordBeginTime);//开始时间
        TextView recordEndTime = findViewById(R.id.recordEndTime);//结束时间
        Button searchProductScreen = findViewById(R.id.searchProductScreen);//查询
        Button closeProductScreen = findViewById(R.id.closeProductScreen);//关闭

        findViewById(R.id.productScreen).setOnClickListener(v -> {
            screenContent.setVisibility(View.VISIBLE);

            if (productNameScreenText != null && !"".equalsIgnoreCase(productNameScreenText)) {
                productNameScreen.setText(productNameScreenText);
            }
            if (productPriceMinScreenText != null && !"".equalsIgnoreCase(productPriceMinScreenText)) {
                productPriceMinScreen.setText(productPriceMinScreenText);
            }
            if (productPriceMaxScreenText != null && !"".equalsIgnoreCase(productPriceMaxScreenText)) {
                productPriceMaxScreen.setText(productPriceMaxScreenText);
            }
            if (recordBeginTimeText != null && !"".equalsIgnoreCase(recordBeginTimeText)) {
                recordBeginTime.setText(recordBeginTimeText);
            }
            recordBeginTime.setOnClickListener(view -> choseDate(recordBeginTime));
            if (recordEndTimeText != null && !"".equalsIgnoreCase(recordEndTimeText)) {
                recordEndTime.setText(recordEndTimeText);
            }
            recordEndTime.setOnClickListener(view -> choseDate(recordEndTime));
        });
        //点击查询
        searchProductScreen.setOnClickListener(v -> {
            sqlParam = " and pid='" + pid + "'";
            productNameScreenText = productNameScreen.getText().toString();//商品名称

            if (!"".equalsIgnoreCase(productNameScreenText)) {
                sqlParam += " and a.product_name  like '%" + productNameScreenText + "%' ";
            }

            productPriceMinScreenText = productPriceMinScreen.getText().toString();//商品价格最小值
            if (!"".equalsIgnoreCase(productPriceMinScreenText)) {
                sqlParam += " and a.product_price  >=" + productPriceMinScreenText;
            }

            productPriceMaxScreenText = productPriceMaxScreen.getText().toString();//商品价格最大值
            if (!"".equalsIgnoreCase(productPriceMaxScreenText)) {
                sqlParam += " and a.product_price  <=" + productPriceMaxScreenText;
            }
            recordBeginTimeText = recordBeginTime.getText().toString();//开始时间
            if (!"".equalsIgnoreCase(recordBeginTimeText)) {
                sqlParam += " and a.time >=" + recordBeginTimeText.replace("/", "") + "000000";
            }
            recordEndTimeText = recordEndTime.getText().toString();//结束时间
            if (!"".equalsIgnoreCase(recordEndTimeText)) {
                sqlParam += " and a.time <=" + recordEndTimeText.replace("/", "") + "235959";
            }

            List<ProductPojo> searchProductPojos = productDao.queryInfo(0, 0, sqlParam);
            items.clear();
            items.addAll(searchProductPojos);
            adapter.notifyDataSetChanged();
            mathPrice();
        });

        closeProductScreen.setOnClickListener(v -> {
            screenContent.setVisibility(View.GONE);
            sqlParam = null;
            productNameScreenText = null;
            productPriceMinScreenText = null;
            productPriceMaxScreenText = null;
            recordBeginTimeText = null;
            recordEndTimeText = null;
            offset = 0;
            limit = 10;
            sqlParam = " and pid='" + pid + "'";
            List<ProductPojo> productPojos = productDao.queryInfo(offset, limit, sqlParam);
            items.clear();
            items.addAll(productPojos);
            adapter.notifyDataSetChanged();


            productNameScreen.setText("");
            productPriceMinScreen.setText("");
            productPriceMaxScreen.setText("");
            recordBeginTime.setText("");
            recordEndTime.setText("");

            mathPrice();
        });
        //客户
        try {
            TextView productTranName = findViewById(R.id.productTranName);//客户
            ClientPojo clientPojo = clientDao.queryClientInfo(pid);
            productTranName.setText(clientPojo.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void init() {
        items = productDao.queryInfo(offset, limit, " and a.pid='" + pid + "'");
        // 填充items数据
        historicalEmpty = findViewById(R.id.historicalEmpty);
        if (items.size() > 0) {
            historicalEmpty.setVisibility(View.GONE);
        } else {
            historicalEmpty.setVisibility(View.VISIBLE);
        }
        //创建一个适配器对象，传一个集合进去给适配器
        adapter = new RecyclerProductViewAdapter(items, this);
        //设置垂直还是水平，三元表达式
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(RecyclerView.VERTICAL);

        adapter.setProjectInterface(new OptInterface());

        //设置方向
        manager.setReverseLayout(false);

        //把设置好的方向和排版给RecyclerView
        recyclerView.setLayoutManager(manager);

        //设置适配器器
        recyclerView.setAdapter(adapter);
    }


    String picFilePath;//拍照录屏的照片路径
    TextView mediaSum;
    int photo = 0;
    int video = 0;
    MediaPagerAdapter mediaPagerAdapter;
    List<String> picList;

    private class OptInterface implements RecyclerProductViewAdapter.ProjectInterface {

        @Override
        public void optProject(int type, ProductPojo dataBean, boolean isChecked) {
            /**
             * type 1:点击多选框;2、删除；3、查看照片视频
             */
            if (type == 2) {
                //删除
                AlertDialog.Builder builder = new AlertDialog.Builder(TranProductActivity.this);
                builder.setTitle("提示");
                builder.setMessage("您确定删除吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        int remove = productDao.delInfo(String.valueOf(dataBean.getId()));
                        String msg = "删除失败";
                        if (remove != -1) {
                            msg = "删除成功";
                        }
                        Toast.makeText(TranProductActivity.this, msg, Toast.LENGTH_LONG).show();
                        items.remove(dataBean);
                        adapter.notifyDataSetChanged();
                        /**
                         * -------------------------------------------重新计算
                         */
                        ClientPojo clientPojo = clientDao.queryClientInfo(pid);
                        int totalProduct = clientPojo.getTotalProduct() - 1;
                        Long productPrice = Long.parseLong(clientPojo.getTotalPrice().replace(",", "")) - Long.parseLong(dataBean.getProductPrice().replace(",", ""));
                        String dealPrice = Utils.getNumlStr(productPrice.toString());
                        clientDao.updateSumInfo(pid, String.valueOf(totalProduct), dealPrice.replace(",", ""));

                        mathPrice();
                        upload.removeProdoctInfo(dataBean.getId());
                    }
                });
                builder.setNeutralButton("取消", null);
                builder.show(); //调用show()方法来展示对话框
            } else if (type == 3) {
                //查看照片视频
                View view1 = LayoutInflater.from(TranProductActivity.this).inflate(R.layout.activity_media_page, null);
                LinearLayout mediaLayout = view1.findViewById(R.id.mediaLayout);
                mediaSum = view1.findViewById(R.id.mediaSum);
                String mult = dataBean.getMult();
                picList = JSONArray.parseArray(mult, String.class);
                photo = 0;
                video = 0;

                /**
                 * 拍照
                 */
                view1.findViewById(R.id.takePicture).setOnClickListener(v -> {
                    if (ContextCompat.checkSelfPermission(TranProductActivity.this, Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(TranProductActivity.this);
                        builder.setTitle("提示");
                        builder.setMessage("需要获取相机、媒体权限才能进行拍照，是否授权？");
                        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                ActivityCompat.requestPermissions(TranProductActivity.this,
                                        new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                        600);

                            }
                        });
                        builder.setNeutralButton("否", null);
                        builder.show(); //调用show()方法来展示对话框
                    } else {
                        photo(1111);
                    }
                });

                /**
                 * 录屏
                 */
                view1.findViewById(R.id.videoRecord).setOnClickListener(v -> {
                    if (ContextCompat.checkSelfPermission(TranProductActivity.this, Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED) {

                        AlertDialog.Builder builder = new AlertDialog.Builder(TranProductActivity.this);
                        builder.setTitle("提示");
                        builder.setMessage("需要获取相机、媒体权限才能进行录像，是否授权？");
                        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                ActivityCompat.requestPermissions(TranProductActivity.this,
                                        new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                        601);
                            }
                        });
                        builder.setNeutralButton("否", null);
                        builder.show(); //调用show()方法来展示对话框
                    } else {
                        video(2222);
                    }
                });

                /**
                 * 选择相册
                 */
                view1.findViewById(R.id.chosePhotoAlbum).setOnClickListener(v -> {
                    if (ContextCompat.checkSelfPermission(TranProductActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {

                        AlertDialog.Builder builder = new AlertDialog.Builder(TranProductActivity.this);
                        builder.setTitle("提示");
                        builder.setMessage("需要获取媒体权限才能完成相册选择，是否授权？");
                        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                ActivityCompat.requestPermissions(TranProductActivity.this,
                                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                        602);
                            }
                        });
                        builder.setNeutralButton("否", null);
                        builder.show(); //调用show()方法来展示对话框
                    } else {
                        photoAlbum(4567);
                    }
                });


                if (picList == null) {
                    picList = new ArrayList<>();
                } else {
                    for (String path : picList) {
                        if (path.contains(".mp4")) {
                            video++;
                        } else {
                            photo++;
                        }
                    }

                }

                mediaSum.setText("照片" + photo + "张；视频" + video + "个");


                mediaPagerAdapter = new MediaPagerAdapter(TranProductActivity.this, picList, type);
                ViewPager viewPager = view1.findViewById(R.id.viewPager);//录像
                viewPager.setAdapter(mediaPagerAdapter);
                mediaPagerAdapter.setOnItemDeleteListener(new MediaPagerAdapter.OnItemDeleteListener() {
                    @Override
                    public void DeleteItem(String filePath, int type) {
                        Constants.deleteFile(filePath);
                        picList.remove(filePath);
                        mediaPagerAdapter.notifyDataSetChanged();
                        if (filePath.contains(".mp4")) {
                            video--;
                        } else {
                            photo--;
                        }
                        mediaSum.setText("照片" + photo + "张；视频" + video + "个");
                    }
                });

                AlertDialog.Builder builder123 = new AlertDialog.Builder(TranProductActivity.this);
                builder123.setView(view1);
                builder123.setCancelable(false);
                builder123.setNeutralButton("关闭", null);
                builder123.setPositiveButton("保存", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        String mult = "";
                        if (picList != null && picList.size() > 0) {
                            mult = JSON.toJSONString(picList);
                        }
                        productDao.updateInfoMult(String.valueOf(dataBean.getId()), mult, photo, video);
                        int i = items.indexOf(dataBean);
                        dataBean.setMult(mult);
                        items.remove(dataBean);
                        items.add(i, dataBean);
                        adapter.notifyDataSetChanged();
                        ToastUtil.show(TranProductActivity.this, "保存成功");

                        ProductPojo productPojo = productDao.queryProductPojoById(dataBean.getId());
                        upload.modifyProductInfo(productPojo);
                    }
                });
                AlertDialog alertDialog = builder123.create();
                alertDialog.show();

                //获取屏幕分辨率
                DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();

                int height = metrics.heightPixels;

                // 设置对话框的高度
                WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
                layoutParams.copyFrom(alertDialog.getWindow().getAttributes());
                layoutParams.height = height / 2; // 设置所需的高度，单位为像素
                alertDialog.getWindow().setAttributes(layoutParams);
            } else {
                //修改
                View view = LayoutInflater.from(TranProductActivity.this).inflate(R.layout.tran_product_modify, null);
                EditText name = view.findViewById(R.id.name);
                name.setText(dataBean.getProductName());
                EditText price = view.findViewById(R.id.price);
                String productPrice = dataBean.getProductPrice();

                String dealPrice = Utils.getNumlStr(productPrice);

                price.setText(dealPrice);
                AlertDialog.Builder builder123 = new AlertDialog.Builder(TranProductActivity.this);
                builder123.setView(view);
                builder123.setTitle("信息修改");
                builder123.setCancelable(false);
                builder123.setPositiveButton("确定", null);
                builder123.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                AlertDialog alertDialog = builder123.create();
                alertDialog.show();
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                        String replace4 = price.getText().toString().replace(",", "");
                        String dealPrice1 = Utils.getNumlStr(replace4);
                        productDao.updateInfo(dataBean.getId() + "", name.getText().toString(), dealPrice1);
                        ToastUtil.show(TranProductActivity.this, "修改成功");

                        /**
                         * -------------------------------------------重新计算--2024年10月11日15:20:34，重点查看一下
                         */
                        ClientPojo clientPojo = clientDao.queryClientInfo(pid);
                        int totalProduct = clientPojo.getTotalProduct();

                        String s = price.getText().toString();
                        String replace = s.replace(",", "");

                        Long endPrice = Long.parseLong(replace);//修改后的价格


                        String productPrice2 = dataBean.getProductPrice();
                        String replace1 = productPrice2.replace(",", "");
                        Long beginPrie = Long.parseLong(replace1);//修改前的价格

                        Long nowPrice = endPrice - beginPrie;//现在的价格

                        String totalPrice = clientPojo.getTotalPrice();
                        String replace2 = totalPrice.replace(",", "");
                        Long numl = Long.parseLong(replace2);
                        Long l = numl + nowPrice;

                        String s1 = Utils.getNumlStr(l.toString());
                        String replace3 = s1.replace(",", "");
                        clientDao.updateSumInfo(pid, String.valueOf(totalProduct), replace3);


                        int i = items.indexOf(dataBean);
                        items.remove(dataBean);
                        dataBean.setProductName(name.getText().toString());
                        try {
                            dataBean.setProductPrice(String.valueOf(endPrice));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        items.add(i, dataBean);
                        adapter.notifyDataSetChanged();
                        mathPrice();

                        ProductPojo productPojo = productDao.queryProductPojoById(dataBean.getId());
                        upload.modifyProductInfo(productPojo);

                    }
                });

            }
        }
    }


    //拍照
    private void photo(int RESULT_CODE) {
        try {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                String filename = UUID.randomUUID().toString();
                File imageFile = File.createTempFile(filename, ".jpg", storageDir);
                filePath = imageFile.getPath();
                Uri uri = FileProvider.getUriForFile(this, "com.ptbuy.fileprovider", imageFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(takePictureIntent, RESULT_CODE);
//                register.launch(takePictureIntent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //录像
    private void video(int RESULT_CODE) {
        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
            try {
                File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                String filename = UUID.randomUUID().toString();
                File imageFile = File.createTempFile(filename, ".mp4", storageDir);
                filePath = imageFile.getPath();
                Uri uri = FileProvider.getUriForFile(this, "com.ptbuy.fileprovider", imageFile);
                takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(takeVideoIntent, RESULT_CODE);
//                register.launch(takeVideoIntent);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //选择相册
    private void photoAlbum(int RESULT_CODE) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");  // 任意类型的文件
        startActivityForResult(intent, RESULT_CODE);
//        register.launch(intent);
    }

    String mytotalProduct;
    String mytotalPrice;

    @SuppressLint("SetTextI18n")
    private void mathPrice() {
        Long sum = 0L;
        for (ProductPojo pp : items) {
            sum += Long.parseLong(pp.getProductPrice().replace(",", ""));
        }
        String dealPrice = Utils.getNumlStr(sum.toString());
        mytotalPrice = dealPrice;
        numTotalPrice.setText(dealPrice);
        mytotalProduct = String.valueOf(items.size());
        //总件数
        numTotalProduct.setText(String.valueOf(items.size()));
    }


    /*
     * 设置刷新的方法
     * */
    private void setRefresh() {

        //设置头部刷新的样式
        smartRefreshLayout.setRefreshHeader(new BezierRadarHeader(this));
        //设置页脚刷新的样式
        smartRefreshLayout.setRefreshFooter(new BallPulseFooter(this));
        //设置头部刷新时间监听
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                smartRefreshLayout.finishRefresh(500/*,false*/);//传入false表示刷新失败
//                //添加一条新数据，再最开头的位置
//                offset = 0;
//                items = productDao.queryInfo(offset, limit, sqlParam);
//                adapter.notifyDataSetChanged();
            }
        });
        /**
         * 上拉加载更多-
         */

        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                smartRefreshLayout.finishLoadMore(999);///延迟999毫秒后结束刷新
                offset = offset + limit;
                if (items.size() == 0 || items.size() < 10) {
                    smartRefreshLayout.finishLoadMore(true);
                    offset = offset - limit;
                    Toast.makeText(TranProductActivity.this, "到底了", Toast.LENGTH_SHORT).show();
                    return;
                }

                List<ProductPojo> dataBean = productDao.queryInfo(offset, limit, sqlParam);

                if (dataBean.size() == 0) {
                    smartRefreshLayout.finishLoadMore(true);
                    offset = offset - limit;
                    Toast.makeText(TranProductActivity.this, "到底了", Toast.LENGTH_SHORT).show();
                } else {

                    smartRefreshLayout.finishLoadMore(true);
                    //添加一条新数据，再最后的位置
                    for (int i = 0; i < dataBean.size(); i++) {
                        items.add(items.size(), dataBean.get(i));
                    }
                    adapter.notifyDataSetChanged();

                    Toast.makeText(TranProductActivity.this, "刷新成功", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }


    private void back() {

        Intent intent = new Intent(this, TranRecordActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
        }
        return false;
    }

    int exportType = 0;

    //导出
    private void recordExport() {
        // 定义一个字符串数组作为单选项
        String[] items = {"导出商品确认单", "导出Excel"};

        // 创建AlertDialog
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择导出类型");
        builder.setCancelable(false);
        builder.setSingleChoiceItems(items, exportType, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 这里的which参数表示选中的单选按钮的索引
                // 可以在这里处理选中事件，例如更新UI或者存储选中的值
                exportType = which;
            }
        });
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", null);

        // 创建并显示对话框
        AlertDialog dialog = builder.create();
        dialog.show();

        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 检查是否已经授予权限
                if (ContextCompat.checkSelfPermission(TranProductActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    // 请求权限
                    ActivityCompat.requestPermissions(TranProductActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    // 已经授予权限，执行导出Excel文件的操作
                    if (exportType != 2) {
                        dialog.dismiss();
                    }
                    exportFile();
                }
            }
        });
    }

    ExportDao exportDao;
    List<ProductPojo> productPojos;

    String clientPojoID = null;

    private void exportFile() {
        if (exportDao == null) {
            exportDao = new ExportDao();
        }

        productPojos = productDao.queryInfo(0, 0, " and pid ='" + pid + "'");

        if (exportType == 0) {
            //导出PDF
            ClientPojo clientPojo = clientDao.queryClientInfo(pid);
            clientPojoID = clientPojo.getId();
            String signatureFilePath = clientPojo.getSignatureFilePath();
            if (signatureFilePath == null) {
                //删除
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("提示");
                builder.setMessage("客户还未签字确认是否签字确认");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        Intent intent = new Intent(TranProductActivity.this, SingDialogAcvity.class);
                        startActivityForResult(intent, 888);
                    }
                });
                builder.setNeutralButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        exportPdf(productPojos, null);
                    }
                });
                builder.show(); //调用show()方法来展示对话框
            } else {
                exportPdf(productPojos, signatureFilePath);
            }

        }
        if (exportType == 1) {
            //导出Excel
            ExportUtils.exportExcel(productPojos, this, new ExportMsgCall() {
                @Override
                public void exportFile(String backFilePath) {
                    if (backFilePath == null) {
                        Message obtainMessage = mHandler.obtainMessage();
                        obtainMessage.what = 3;
                        mHandler.sendMessage(obtainMessage);
                    } else {
                        filePath = backFilePath;
                        Message obtainMessage = mHandler.obtainMessage();
                        obtainMessage.what = 2;
                        mHandler.sendMessage(obtainMessage);

                    }
                }
            });
        } else if (exportType == 2) {
            //导出计录
            exportRecords();
        }
    }

    private void exportPdf(List<ProductPojo> productPojos, String signatureFilePath) {

        ExportUtils.exportPDF(productPojos, signatureFilePath, this, mytotalProduct, mytotalPrice, new ExportMsgCall() {
            @Override
            public void exportFile(String backFilePath) {
                if (backFilePath == null) {
                    Message obtainMessage = mHandler.obtainMessage();
                    obtainMessage.what = 3;
                    mHandler.sendMessage(obtainMessage);
                } else {
                    filePath = backFilePath;
                    Message obtainMessage = mHandler.obtainMessage();
                    obtainMessage.what = 2;
                    mHandler.sendMessage(obtainMessage);
                }
            }
        });
    }

    String filePath;

    List<ExportPojo> exportPojos;
    ExportViewAdapter exportViewAdapter;

    //导出计录
    private void exportRecords() {
        View view1 = LayoutInflater.from(this).inflate(R.layout.tran_historical_export, null);
        ListView listExport = view1.findViewById(R.id.listExport);

        exportPojos = exportDao.queryExportPojo();

        exportViewAdapter = new ExportViewAdapter(this, exportPojos);
        exportViewAdapter.setProjectInterface(new MyExportViewInterface());
        listExport.setAdapter(exportViewAdapter);


        AlertDialog.Builder builder123 = new AlertDialog.Builder(this);
        builder123.setTitle("导出记录");
        builder123.setView(view1);
        builder123.setCancelable(true);
        builder123.setPositiveButton("关闭", null);
        AlertDialog alertDialog = builder123.create();
        alertDialog.show();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p = alertDialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.8);   //高度设置为屏幕的0.3
        alertDialog.getWindow().setAttributes(p);     //设置生效
    }

    private class MyExportViewInterface implements ExportViewAdapter.ExportViewInterface {

        @Override
        public void opt(ExportPojo dataBean) {
            AlertDialog.Builder builder = new AlertDialog.Builder(TranProductActivity.this);
            builder.setTitle("提示");
            builder.setMessage("您确定删除吗？");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    exportPojos.remove(dataBean);
                    exportDao.delInfo(dataBean.getId());
                    exportViewAdapter.notifyDataSetChanged();
                    Constants.deleteFile(dataBean.getExportFilePath());
                }
            });
            builder.setNeutralButton("取消", null);
            builder.show(); //调用show()方法来展示对话框

        }
    }

    private Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 2:
                    exportSuccess();
                    break;
                case 3:
                    ToastUtil.show(TranProductActivity.this, "导出异常");
                    break;
            }
        }

        ;
    };

    private void choseDate(TextView timeView) {
        // 创建并显示 DatePickerDialog
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        // 处理选择的日期
                        int i = month + 1;
                        String mon = String.valueOf(i);
                        if (i < 10) {
                            mon = "0" + i;
                        }
                        String day = String.valueOf(dayOfMonth);
                        if (dayOfMonth < 10) {
                            day = "0" + dayOfMonth;
                        }
                        String selectedDate = year + "/" + mon + "/" + day;
                        timeView.setText(selectedDate);
                    }
                },
                year, month, day
        );

        // 显示 DatePickerDialog
        datePickerDialog.show();
    }


    private void exportSuccess() {
        AlertDialog.Builder builder = new AlertDialog.Builder(TranProductActivity.this);
        builder.setTitle("导出成功");
        builder.setMessage("存放位置：" + filePath);
        builder.setPositiveButton("打开文件", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                File file = new File(filePath);
                if (file.exists()) {
                    MineType.openFile(TranProductActivity.this, file);
                } else {
                    ToastUtil.show(TranProductActivity.this, "文件丢失");
                }
            }
        });
        builder.setNeutralButton("关闭", null);
        builder.show(); //调用show()方法来展示对话框
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //申请文件读写权限
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            exportFile();
        } else if (requestCode == 600) {
            photo(1111);
        } else if (requestCode == 601) {
            video(2222);
        } else if (requestCode == 602) {
            photoAlbum(4567);
        }
    }

    String singaturePath;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1111 && resultCode == RESULT_OK) {
            // 拍照成功后的处理
            // 可以在这里获取录像的Uri等信息
            if (picFilePath != null) {
                File file = new File(picFilePath);
                if (file.exists()) {
                    picList.add(picFilePath);
                    mediaPagerAdapter.notifyDataSetChanged();
                    photo++;
                    mediaSum.setText("照片" + photo + "张；视频" + video + "个");
                }
            }
        } else if (requestCode == 2222 && resultCode == RESULT_OK) {
            // 录像成功后的处理
            // 可以在这里获取录像的Uri等信息
            if (picFilePath != null) {
                File file = new File(picFilePath);
                if (file.exists()) {
                    picList.add(picFilePath);
                    mediaPagerAdapter.notifyDataSetChanged();
                    video++;
                    mediaSum.setText("照片" + photo + "张；视频" + video + "个");
                }
            }
        } else if (requestCode == 4567 && resultCode == RESULT_OK && data != null) {

            Uri uri = data.getData();
            if (uri != null) {
                // 获取图片的真实路径
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                if (cursor != null) {
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String filePath = cursor.getString(columnIndex);
                    cursor.close();
                    // 录像成功后的处理
                    // 可以在这里获取录像的Uri等信息
                    File file = new File(filePath);
                    if (file.exists()) {
                        picList.add(filePath);
                        mediaPagerAdapter.notifyDataSetChanged();
                        photo++;
                        mediaSum.setText("照片" + photo + "张；视频" + video + "个");
                    }
                }
            }


        } else if (requestCode == 1111 || requestCode == 2222) {
            try {
                if (picFilePath != null) {
                    File file = new File(picFilePath);
                    if (file.exists()) {
                        file.delete();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (requestCode == 888 && resultCode == RESULT_OK && data != null) {
            singaturePath = data.getExtras().getString("path");
            clientDao.updateSignatureFilePath(clientPojoID, singaturePath);
            exportPdf(productPojos, singaturePath);
        }
    }
}